package com.xb.loan.log.exception;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class ErrorCodeManager {
    
	// 用错误码的名字做为key存储
	public final static Map<String, String> CODE_MSG_STORAGE = new HashMap<String, String>();
	// 用错误码的错误代码作为key存储
	public final static Map<String, ErrorCode> CODE_BEAN_STORAGE = new HashMap<String, ErrorCode>();
	// 配置文件默认路径
	public final static String CFG_PATH = getCfgPath();

	public static String getCfgPath(){
		
		try {
			File f = ResourceUtils.getFile("classpath:exception/");
			
			if(f.isDirectory()){
				
				return f.getAbsolutePath();
			}
		} catch (FileNotFoundException e) {
			
			e.printStackTrace();
		}
		
		return "";
	}
	
	static{
		init();
	}

	/**
	 * 通过异常代码获取异常配置信息
	 */
	public static ErrorCode getErrorCode(String errorCode) {
		 ErrorCode code = CODE_BEAN_STORAGE.get(errorCode);
		 if(code == null){
			 code = new ErrorCode();
			 code.setCode(errorCode);
			 code.setMsg("unkown");
		 }
		 return code;
	}

	public static String getErrorMsg(String errorCode) {
		 String msg = CODE_MSG_STORAGE.get(errorCode);
		 if(msg == null){
			 return "unkown";
		 }
		 return msg;
	}
	
	public synchronized static void init() {
		File errorXmlDir = new File(CFG_PATH);
		File[] errorXmlFiles = errorXmlDir.listFiles();
		for(File errorXml:errorXmlFiles){
			if(errorXml.isFile() && errorXml.getName().startsWith("errorcode")){
				InputStream in = null;
				try {
					in = new FileInputStream(errorXml.getAbsolutePath());
					Document doc = new SAXReader().read(in);
					Element root = doc.getRootElement();
					List<Node> cfgNodes = root.selectNodes("errorcode");
					if (cfgNodes != null && cfgNodes.size() > 0) {
						for (Node node : cfgNodes) {
							ErrorCode errorCode = new ErrorCode();
		                    errorCode.setCode(node.selectSingleNode("@code").getText());
		                    errorCode.setMsg(node.selectSingleNode("@msg").getText());
		                    errorCode.setName(node.selectSingleNode("@name").getText());
		                    CODE_BEAN_STORAGE.put(errorCode.getCode(), errorCode);
		                    CODE_MSG_STORAGE.put(node.selectSingleNode("@code").getText(), 
		                    		node.selectSingleNode("@msg").getText());
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					if (in != null) {
						try {
							in.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
				
			}
		}
		
	}
	public static void main(String[] args) {
        System.out.println(ErrorCodeManager.getErrorCode("1600").getMsg());
    }
}
